<template>
  <div>
    <el-table
      v-loading="loading"
      :data="dataSource"
      :row-key="rowKey"
      :size="size"
      :default-expand-all="defaultExpandAll"
      :tree-props="treeProps"
      @row-click="$emit('rowClick', arguments)"
    >
      <el-table-column v-for="(item, index) of tableProps" :key="index" :label="item.label">
        <template slot-scope="scope">
          <span v-if="item.dict">{{ dictTest(item.dict, scope.row[item.index]) }}</span>
          <span v-else>{{ scope.row[item.index] || '空' }}</span>
        </template>
      </el-table-column>
      <slot name="tool" />
    </el-table>
    <ms-pagination v-if="pagination" :count="count" @changeCurrentPage="handleChangeData" @changePageSize="handleChangeSize" />
  </div>
</template>

<script>
import { getPageData } from '@/api/common/page'
import { getDict } from '@/api/sys/dict'
import MsPagination from './MsPagination'

export default {
  components: {
    MsPagination
  },
  props: {
    tableProps: {
      type: Array,
      required: true
    },
    dataApi: {
      type: String,
      require: true
    },
    treeProps: {
      type: Object
    },
    rowKey: {
      type: String,
      default: 'id'
    },
    pagination: {
      type: Boolean,
      default: true
    },
    size: {
      type: String,
      default: 'medium'
    },
    defaultExpandAll: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      dataSource: [],
      count: 0,
      pages: {
        page: 1,
        limit: 10,
        info: {}
      },
      loading: true,
      dict: {}
    }
  },
  methods: {
    async dataFresh(page = this.pages.page, limit = this.pages.limit, info = this.pages.info) {
      this.loading = true
      // 获取关联字典对应表格
      await this.tableProps.forEach(async item => {
        if (item.dict) {
          await this.formatDict(item.dict)
        }
      })
      // merge查询
      const obj = { page, limit, ...info }
      await getPageData(this.dataApi, obj).then(res => {
        console.log(this.dict)
        this.dataSource = res.obj.records
        this.count = res.obj.total
        this.loading = false
      })
    },
    handleChangeData(val) {
      this.pages.page = val
      this.dataFresh(val)
    },
    handleChangeSize(val) {
      this.pages.limit = val
      this.dataFresh(this.pages.page, val)
    },
    dictTest(dict, value) {
      return this.dict[dict] ? this.dict[dict][value] : '-'
    },
    async formatDict(dict) {
      if (!this.dict[dict]) {
        const dictVal = {}
        await getDict(dict).then(async res => {
          res.obj.forEach(item => {
            dictVal[item.code] = item.dictValue
          })
          this.dict[dict] = dictVal
        })
      }
    }
  }
}
</script>
